var resultKey = "examresult";
var doneKey = "done";
var lastIndexKey = "lastIndex";

app.factory("treasuryExamService", ["$http", "localStorageService", function ($http, localStorageService) {
    var promise;

    var header;
    if (!isLocalDebug) {
        header = {
            'ApiKey': getParameterFromUrl('ApiKey'),
            'DeviceId': getParameterFromUrl('DeviceId'),
            'AuthToken': encodeURIComponent(getParameterFromUrl('Token')),
            'IsTokenEncrypted': false
        };
    }
    else {
        header = {
            'ApiKey': "4feeeee1cc094f2d9949cb33264c30cf",
            'DeviceId': "dongmingdeviceid1234",
            'AuthToken': "test3token",//"2c47766ea96c407684d1d82792efa4fe", //"43f30d39557c43ed8389678f37ad54ae",//"a242cdc11eaf4c63a837b8e79b73c404", //"30b98df1a75449b9a89c2f05a8831a48",
            'isTokenEncrypted': false
        };
    }

    var apiUrl = "http://" + domain + "/api/";
    var apiVersion = "v1/";
    var prefix = apiUrl + apiVersion + "/";

    $http.defaults.headers.common = header;

    var service = {
        getExamList: function () {
            promise = $http.get("dummy/subject_list.json?t=" + Math.random() * 100000).then(function (response) {
                //dummy data, the structure is different with real data.
                return response.data;
            });
            return promise;
        },
        getExam: function (id) {
            promise = $http.get("dummy/" + id + ".json?t=" + Math.random() * 100000).then(function (response) {
                //dummy data, the structure is different with real data.
                return response.data;
            });
            return promise;
        },
        getSectionList: function (subjectId) {
            promise = $http.get("dummy/section_list.json?t=" + Math.random() * 100000).then(function (response) {
                //dummy data, the structure is different with real data.
                var result = [];
                for (var i = 0; i < response.data.sections.length; i++) {
                    if (response.data.sections[i].subjectId == subjectId) {
                        result.push(response.data.sections[i]);
                    }
                }
                return result;
            });
            return promise;
        },
        getErrors: function (examId) {
            return errorIds = localStorageService.get(examId);
        },
        setError: function (examId, questionId) {
            var errorIds = localStorageService.get(examId);
            if (!errorIds)
                errorIds = [];

            if (errorIds.indexOf(questionId) == -1) {
                errorIds.push(questionId);
                localStorageService.set(examId, errorIds);
            }
        },
        removeError: function (examId) {
            var errorIds = localStorageService.get(examId);
            if (errorIds) {
                localStorageService.set(examId, []);
            }
        },
        getMockQuestion: function (arr, num) {
            var temp_array = [];
            for (var index in arr) {
                temp_array.push(arr[index]);
            }
            var return_array = [];
            for (var i = 0; i < num; i++) {
                if (temp_array.length > 0) {
                    var arrIndex = Math.floor(Math.random() * temp_array.length);
                    return_array[i] = temp_array[arrIndex];
                    temp_array.splice(arrIndex, 1);
                } else {
                    break;
                }
            }
            return return_array;
        },
        addExamResult: function (examId, res) {
            if (!res)
                return -1;
            var results = localStorageService.get(getResultKey(examId));
            if (!results)
                results = [];
            results.push(res);
            localStorageService.set(getResultKey(examId), results);
            return results.length - 1;
        },
        getExamResult: function (examId, index) {
            var results = localStorageService.get(getResultKey(examId));
            if (!results || index >= results.length)
                return null;
            else {
                return results[index];
            }
        },
        getExamResults: function (examId) {
            var results = localStorageService.get(getResultKey(examId));
            if (!results)
                return [];
            else {
                return results.reverse();
            }
        },
        markAsDone: function (examId, questionId) {
            var key = getDoneKey(examId);
            var dones = localStorageService.get(key);
            if (!dones)
                dones = [];

            if (dones.indexOf(questionId) == -1) {
                dones.push(questionId);
                localStorageService.set(key, dones);
            }
        },
        getUndoQuestions: function (arr, num, examId) {
            var key = getDoneKey(examId);
            var dones = localStorageService.get(key);
            if (dones) {
                var doneTemp = [];
                var undoTemps = [];
                for (var i = 0; i < arr.length; i++) {
                    var item = arr[i];
                    if (dones.indexOf(item.id) == -1) {
                        undoTemps.push(item);
                    }
                    else {
                        doneTemp.push(item);
                    }
                }

                if (undoTemps.length >= num) {
                    return getRandomArray(undoTemps, num);
                }
                else {
                    var remainLength = num - undoTemps.length;
                    var undos = getRandomArray(undoTemps, undoTemps.length);
                    var dones = getRandomArray(doneTemp, remainLength);
                    for (var i = 0; i < dones.length; i++) {
                        undos.push(dones[i]);
                    }
                    return undos;
                }
            }
            else {
                return getRandomArray(arr, num);
            }
        },
        getQuestionsBySection: function (arr, sectionId) {
            var return_array = [];
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].sectionId == sectionId) {
                    return_array.push(arr[i]);
                }
            }
            return return_array;
        },
        getQuestionById: function (arr, questionId) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].id * 1 == questionId) {
                    return arr[i];
                }
            }
            return null;
        },
        getLastIndex: function (examId) {
            var result = localStorageService.get(getLastIndexKey(examId));
            if (!result)
                return 0;
            else {
                return result;
            }
        },
        setLastIndex: function (examId, index) {
            localStorageService.set(getLastIndexKey(examId), index);
        },
        getLastIndexForSection: function (examId, sectionId) {
            var result = localStorageService.get(getLastIndexKeyForSection(examId, sectionId));
            if (!result)
                return 0;
            else {
                return result;
            }
        },
        setLastIndexForSection: function (examId, sectionId, index) {
            localStorageService.set(getLastIndexKeyForSection(examId, sectionId), index);
        },
        getVideo: function (options) {
            //POST api/v1/DrivingTest/GetVideo?subjectType={snsClubId}&itemId={itemId}
            promise = $http({
                method: 'GET',
                url: prefix + "DrivingTest/GetVideo",
                params: options
            }).then(function (response) {
                return response.data;
            });
            return promise;
        }
    }
    return service;
}]);

var getResultKey = function (examId) {
    return resultKey + "-" + examId;
};

var getDoneKey = function (examId) {
    return doneKey + "-" + examId;
}

var getLastIndexKey = function (examId) {
    return lastIndexKey + "-" + examId;
}

var getLastIndexKeyForSection = function (examId, sectionId) {
    return lastIndexKey + "-" + examId + "-" + sectionId;
}

var getRandomArray = function (arr, num) {
    var temp_array = [];
    for (var index in arr) {
        temp_array.push(arr[index]);
    }
    var return_array = [];
    for (var i = 0; i < num; i++) {
        if (temp_array.length > 0) {
            var arrIndex = Math.floor(Math.random() * temp_array.length);
            return_array[i] = temp_array[arrIndex];
            temp_array.splice(arrIndex, 1);
        } else {
            break;
        }
    }
    return return_array;
}

app.factory("treasurySubitemService", ["$http", function ($http) {
    var promise;
    var service = {
        getSubject: function (id) {
            promise = $http.get("dummy/" + id + ".json?t=" + Math.random() * 100000).then(function (response) {
                return response.data;
            });
            return promise;
        }
    }
    return service;
}]);

app.factory("treasuryNavigationService", function ($location, $routeParams) {
    //console.log($location.path().split("/"))
    var getBackUrl = function (position) {
        switch (position) {
            case "":
                return function () {
                    if (window.WebViewJavascriptBridge) {
                        WebViewJavascriptBridge.callHandler('exitUIWebView');
                    } else if (browser.versions.android) {
                        jsb.require('exitUIWebView', { "msg": "navigate back" }, function (response) {
                            //Log.log(response);
                        });
                    }
                };
                break;
            default:
                return function () {
                    $location.path("/");
                };
                break;

        }
    };
    return {
        back: function () {
            var returnUrl = $location.search().backUrl;
            //console.log("++++++returnUrl++++++" + returnUrl);
            if (returnUrl) {
                $location.url(returnUrl);
                return;
            }
            var urlKey = $location.path().split("/")[1] || '';
            (getBackUrl(urlKey))();
        }
    }
});